<template>
    <el-header style="background-color: lightgray; text-align: right; font-size: 12px;height: 100px;">
      <el-header style="text-align: right; font-size: 12px;height: 100px;">
      <h1 style="font-size: 30px; text-align: left;">现场挂号</h1>
      </el-header>
           <div class="toolbar">
          <div>系统希望您不再是本系统受众，并提醒您务必谨遵医嘱</div>
      
      <div class="sub-title"></div>
      <div class="demo-basic--square">
        <div class="block">
          <el-avatar shape="square" :size="100" :src="squareUrl" />
        </div>
      </div>

          <h6>小埋大王天下第一！</h6>
             <el-dropdown>
               <el-icon style="margin-right: 8px; margin-top: 1px"
                 ><setting
               /></el-icon>
               <template #dropdown>
                 <el-dropdown-menu>
                   <el-dropdown-item>看啥呢</el-dropdown-item>
                   <el-dropdown-item>有啥好看的</el-dropdown-item>
                   <el-dropdown-item>别看了</el-dropdown-item>
                 </el-dropdown-menu>
               </template>
             </el-dropdown>
             <!-- <span>门诊挂号</span> -->
           </div>
         </el-header>
        
         <el-form ref="ruleFormRef" :rules="rules" :size="formSize" :model="form" label-width="auto"  >
          <el-button style="margin-left: 20px;height: 40px;font-size: 15px;" plain @click="open" type="primary" round>挂号</el-button>
         
          <el-button style="margin-left: 20px;height: 40px;font-size: 15px;" @click="resetForm" type="success" round>清空</el-button>
       <h3>基本信息</h3>
        <div class="basicInfo">
            <el-row>
    <el-col :span="6"><div class="grid-content ep-bg-purple" />   
    <el-form-item label="病历号" prop="orderNo" class="label" style="display: inline-block;">
       <el-input v-model="form.orderNo" placeholder="请输入病历号" />
     </el-form-item></el-col>
    <el-col :span="6"><div class="grid-content ep-bg-purple-light" />
        <el-form-item label="姓名" prop="patientName"  class="label">
       <el-input v-model="form.patientName" placeholder="请输入您的姓名">
       </el-input>
     </el-form-item>
    </el-col>
    <el-col :span="6"><div class="grid-content ep-bg-purple" />
        <el-form-item  label="性别" prop="patientGender"  class="label">
       <el-select v-model="form.patientGender" placeholder="请选择您的性别">
         <el-option label="男" value="男" />
         <el-option  label="女" value="女" />
       </el-select>
     </el-form-item>
    </el-col>
    <el-col :span="6"><div class="grid-content ep-bg-purple-light" />
        <el-form-item label="年龄" prop="age" class="label" >
        <el-input v-model="form.age" placeholder="关关难过关关过"  />
        <el-select v-model="form.ageType" placeholder="请大人和小大人选择年龄类型">
          <el-option label="年" value="年" />
          <el-option label="天" value="天" />
        </el-select>
        
     </el-form-item>
      
    </el-col>
  </el-row>
  <el-row>
    <el-col :span="6"><div class="grid-content ep-bg-purple" />
        <el-form-item prop="birthday" label="出生日期"  class="label" >
       <el-col :span="6">
         <el-date-picker
           v-model="form.birthday"
           type="date"
           placeholder="请选择您的出生日期"
          style="width: 200px;"
         />
       </el-col>
     </el-form-item>
    </el-col>
    <el-col :span="12"><div class="grid-content ep-bg-purple" />
        <el-form-item label="地址" prop="address" class="label" style="display: inline-block;width: 480px;" >
       <el-input v-model="form.address" placeholder="请给我们一个可以及时联系到您的地址"/>
       
     </el-form-item>
    </el-col>
    <el-col :span="6"><div class="grid-content ep-bg-purple-light" />
        <el-form-item label="身份证号" prop="identifyNumber" class="label" >
       <el-input v-model="form.identifyNumber" placeholder="收集身份证号仅作为受医标识"/>
     </el-form-item>
    </el-col>
  </el-row>
    <h3>挂号信息</h3>
    <el-row>
    <el-col :span="6"><div class="grid-content ep-bg-purple-light" />
      <el-form-item label="结算类别" prop="jieMethod" class="label">
       <el-select v-model="form.jieMethod" placeholder="请选择">
         <el-option label="自费" value="1" />
         <el-option label="市医保" value="2" />
         <el-option label="新农合" value="3" />
       </el-select>
     </el-form-item>
    </el-col>
    <el-col :span="6"><div class="grid-content ep-bg-purple" />
      <el-form-item label="看诊日期" prop="orderDate" class="label">
       <input type="text" v-model="form.orderDate" disabled="true"/>
     
     </el-form-item>
    </el-col>
    <el-col :span="6"><div class="grid-content ep-bg-purple-light" />
      <el-form-item label="午别" prop="wuType" class="label">
         <input type="text" v-model="form.wuType"  disabled="true"  />

     </el-form-item>
    </el-col>
    <el-col :span="6"><div class="grid-content ep-bg-purple-dark" />
      <el-form-item label="号别" prop="hao" class="label">
       <el-select @change="fetch1" v-model="form.hao" placeholder="请选择">
         <el-option label="专家号" value=1 />
         <el-option label="主任号" value=2 />
         <el-option label="普通号" value=3 />
       </el-select>
     </el-form-item>
    </el-col>
  </el-row>
  <el-row>
    <el-col :span="6"><div class="grid-content ep-bg-purple-light" />
      <el-form-item label="挂号科室" prop="deptType" class="label">
       <el-select v-model="form.deptType" placeholder="请选择">
        <el-option  v-for="orderDTO in uniqueOrderDTO"  :key="orderDTO.deptId" :label="orderDTO.deptName"  :value="orderDTO.deptId" 
         />
       </el-select>
     </el-form-item>
    </el-col>

    <el-col :span="6"><div class="grid-content ep-bg-purple" />
      <el-form-item label="看诊医生" prop="doctor" class="label">
       <el-select v-model="form.doctor" placeholder="请选择">
         <el-option v-for="orderDTO in OrderDTO" :key="orderDTO.employeeId" :label="orderDTO.employeeName" :value="orderDTO.employeeId"  />
       </el-select>
     </el-form-item>
    </el-col>
    <el-col :span="6"><div class="grid-content ep-bg-purple-light" />
      <el-form-item label="初始号额"  class="label">
       <input type="text" v-if="form.hao==1" value="20"  disabled="true" placeholder="请输入"/>
        <input type="text" v-if="form.hao==2" value="30"  disabled="true"  placeholder="请输入"/>
       <input type="text" v-if="form.hao==3" value="30"  disabled="true"  placeholder="请输入"/>
     </el-form-item>
    </el-col>
    <el-col :span="6"><div class="grid-content ep-bg-purple-li" />
      <el-form-item label="已用号额"  class="label">
        <input type="text" v-if="form.hao==1" v-for="(arr,index) in arrayQ" :value="arr-20"  disabled="true" placeholder="请输入"/>
        <input type="text" v-if="form.hao==2" v-for="(arr,index) in arrayQ" :value="arr-30"  disabled="true" placeholder="请输入"/>
        <input type="text" v-if="form.hao==3" v-for="(arr,index) in arrayQ" :value="arr-30"  disabled="true" placeholder="请输入"/>
     </el-form-item>
    </el-col>
    <el-col :span="6"><div class="grid-content ep-bg-purple-lig" />
      
    </el-col>
  </el-row>
  <el-row>
    <el-col :span="6"><div class="grid-content ep-bg-clasj" />
      <div class="label" style="padding-top: 30px;" > 病历本<el-switch v-model="form.delivery"  
        inline-prompt active-text="是" inactive-text="否" 
        >
      </el-switch></div>
     
    </el-col>
    <el-col :span="6"><div class="grid-content ep-bg-clasj-liht" />
          
     <el-form-item label="应收金额" prop="moneyMust"   class="label">
      <input type="text" v-if="form.hao==1"  value="50"  disabled="true" placeholder="请输入"/>
      <input type="text" v-if="form.hao==2"  value="8"  disabled="true"  placeholder="请输入"/>
      <input type="text" v-if="form.hao==3"  value="20"  disabled="true" placeholder="请输入"/>
     </el-form-item>
    </el-col>
    <el-col :span="6"><div class="grid-content ep-bg-clasj-asd" />
      <el-form-item label="收费方式" prop="moneyMethod" class="label">
       <el-select v-model="form.moneyMethod" placeholder="请选择">
         <el-option label="微信" value="微信" />
         <el-option label="支付宝" value="支付宝" />
         <el-option label="现金" value="现金" />
         <el-option label="医保卡" value="医保卡" />
       </el-select>
     </el-form-item>
    </el-col>
    <el-col :span="6"><div class="grid-content ep-bg-clasj-asd" />
      <el-form-item :rules="rules.registMoney" prop="registMoney" label="收费金额" class="label">
        <el-select v-model="form.registMoney" placeholder="请选择">
         <el-option v-if="form.hao==1" label="100" value="100" />
         <el-option v-if="form.hao==2" label="50.1" value="50.1" />
         <el-option v-if="form.hao==3" label="10" value="10" />
         <el-option v-if="form.hao==3" label="51" value="9"/>
         
       </el-select>
   
     </el-form-item>
    </el-col>
    <el-col :span="6"><div class="grid-content ep-bg-clasj-lit" />
    </el-col>
  </el-row>
    

    </div>
    <div class="class1">

    </div>
   
    <div class="orderInfo">
    </div>
   </el-form>
 
 
 
   </template>
   
   <script lang="ts" setup name="Order">
   
   import {
  Check,
  Delete,
  Edit,
  Message,
  Search,
  Star,
} from '@element-plus/icons-vue'
 import { valueEquals } from 'element-plus';
import axiosInstance from '@/utils/axiosUtils';
import { ref } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { reactive, toRefs } from 'vue'
import { format } from 'date-fns';
import queryString from 'query-string';
import type { ComponentSize, FormInstance, FormRules } from 'element-plus'
const formSize = ref<ComponentSize>('default')
const ruleFormRef = ref<FormInstance>(null)


  function formatDate1(date) {
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0'); // 月份是从0开始的，所以要加1，并确保是两位数
  const day = String(date.getDate()).padStart(2, '0'); // 确保是两位数
  const hours = String(date.getHours()).padStart(2, '0'); // 确保是两位数
  const minutes = String(date.getMinutes()).padStart(2, '0'); // 确保是两位数
  const seconds = String(date.getSeconds()).padStart(2, '0'); // 确保是两位数

  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;


}


const state = reactive({
  squareUrl:
  'https://img1.baidu.com/it/u=2113336262,496117394&fm=253&fmt=auto&app=138&f=JPEG?w=400&h=330',
  sizeList: ['large'] as const,
})

const {  squareUrl,sizeList } = toRefs(state);

interface RuleForm {
  orderNo: string;
  patientName: string;
  patientGender: string;
  age: string;
  ageType: string;
  dataAge: string;
  birthday: string;
  address: string;
  identifyNumber: string;
  orderDate: string;
  date1: string;
  wuType: string;
  deptType: string;
  hao: number;
  doctor: string;
  countBegin: string;
  countUse: string;
  delivery: boolean;
  moneyMust: string;
  moneyMethod: string;
  employeeId: number;
  deptId: number;
  registId: number;
  jieMethod: string;
  registMoney: number;
}
 // do not use same name with ref
 const form = reactive<RuleForm>({
   orderNo:'',
   patientName:'',
   patientGender:'',
   age:'',
   ageType:'',
   dataAge:'',
   birthday:null,
   address:'',
   identifyNumber:'',
   orderDate:formatDate1(new Date()),
   date1:'',
   wuType:new Date().getHours()<12?'上午':'下午',
   deptType:'',
   hao:null,
   doctor:'',
   countBegin:'',
   countUse:'',
   delivery:false,
   moneyMust:'',
   moneyMethod:'',
   employeeId:0,
   deptId:0,
   registId:0,
   jieMethod:'',
   registMoney:0
 });
const rules= reactive<FormRules<RuleForm>>({
    orderNo: [
      { required: true, message: '病历号不能为空', trigger: 'blur' },
      { pattern: /^\d+$/, message: '病历号必须为数字', trigger: 'blur' },
    ],
    patientName: [
      { required: true, message: '姓名不能为空', trigger: 'blur' },
      { pattern: /^[\u4e00-\u9fa5a-zA-Z]+$/, message: '姓名必须为汉字或字母', trigger: 'blur' },
    ],
    patientGender: [
      { required: true, message: '性别不能为空', trigger: 'change' },
    ],
    age: [
      { required: true, message: '年龄不能为空', trigger: 'blur' },
      { pattern: /^(0|[1-9]\d*)$/, message: '年龄必须为正整数', trigger: 'blur' },
    ],
    birthday: [
      { required: true, message: '出生日期不能为空', trigger: 'change' },
    ],
    address: [
      { required: true, message: '地址不能为空', trigger: 'blur' },
    ],
    identifyNumber: [
      { required: true, message: '身份证号不能为空', trigger: 'blur' },
      { pattern: /^\d{15}$|^\d{17}[\dX]$/, message: '身份证号格式不正确', trigger: 'blur' },
    ],
    jieMethod: [
      { required: true, message: '请选结算类别', trigger: 'change' },
    ],
    hao: [
      { required: true, message: '请选择号别', trigger: 'change' },
    ],
    deptType: [
      { required: true, message: '请选择挂号科室', trigger: 'change' },
    ],
    doctor: [
      { required: true, message: '请选择医生', trigger: 'change' },
    ],
    moneyMethod: [
      { required: true, message: '请选择收费方式', trigger: 'change' },
    ],
    registMoney: [
      { required: true, message: '请选择收费金额', trigger: 'change' },
    ]
});

 const OrderDTO=reactive([]);//存储DTO对象信息
 const arrayD=reactive([]);
 const arrayQ=reactive([]);
 const quota=reactive([]);
 const uniqueOrderDTO=reactive([]);
 //清空表单函数
 const resetForm=()=>{
  for(const key in form){
    form[key]='';
  }
 };

 axiosInstance.get("/api/register/getOrderNo?id="+1).then(
  response=>{
    console.log('success'+response.data);
    form.orderNo=response.data;
  }
).catch(error=>{
  console.log('error');
})
//1.获取日志
const fetch1 = async () => {
    if (form.hao !== null) {
        try {
            let resp = await axiosInstance({
                method: "GET",
                url: ('/api/register/getRegistFeeAndCount?hao=' + form.hao)
            });
            console.log(resp.data);

            //使用扩展数组赋值运算符给数组赋值
 OrderDTO.splice(0,OrderDTO.length,...resp.data);
  // 对 OrderDTO 数据去重
  const uniqueDeptIds = Array.from(new Set(OrderDTO.map(item => item.deptId)));
      uniqueOrderDTO.splice(0, uniqueOrderDTO.length, ...uniqueDeptIds.map(deptId => {
        return OrderDTO.find(item => item.deptId === deptId);
      }));
             // 获取第一个属性的名称
const uniqueDeptNames=new Set(OrderDTO.map(item=>item.deptName));
const uniqueQuotas=new Set(OrderDTO.map(item=>item.registQuota));
console.log(uniqueDeptNames); // Set { 1, 2, 3, 4 }
console.log(uniqueQuotas);
 // 转换为数组并更新响应式变量
arrayD.splice(0, arrayD.length, ...Array.from(uniqueDeptNames));
arrayQ.splice(0, arrayQ.length, ...Array.from(uniqueQuotas));
 console.log(quota);
console.log(arrayD);
console.log(arrayQ);
        }
        catch (error) {
            console.log("Error fetching data:", error);
        }
    }
};

    
    
 const open = () => {
  
  console.log('open');
  if (!form.orderNo) {
    ElMessage({
      type: '警告',
      message: '请确保已获取到病历号,重新打开页面',
    });
    return;//退出函数
  }
   
  ElMessageBox.confirm(
    '请确认您的操作',
    '提示：',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'Info:',
    }
  ).then(() => {
     console.log('submit');
 submitForm(ruleFormRef.value);
    })
    .catch(() => {
      ElMessage({
        type: '取消',
        message: '操作已取消',
      });
    });
};
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) 
    return;

  // 验证表单
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      console.log('submit!');
      // 假设表单数据
      const sub = reactive({
        orderNo: form.orderNo,
        patientName: form.patientName,
        patientGender: form.patientGender,
        age: form.age,
        dataAge: form.ageType,
        birthday: format(new Date(form.birthday), 'yyyy-MM-dd'),
        address: form.address,
        identifyNumber: form.identifyNumber,
        wuType: form.wuType,
        deptType: form.deptType,
        hao: form.hao,
        date1: form.orderDate,
        delivery: form.delivery ? '是' : '否',
        moneyMust: form.hao === 1 ? 50 : (form.hao === 2 ? 8 : (form.hao === 3 ? 20 : 0)),
        moneyMethod: form.moneyMethod,
        employeeId: form.doctor,
        deptId: form.deptType, // 确保 deptId 的来源合理
        jieMethod: form.jieMethod,
        registMoney: form.registMoney
      });

      console.log('提交的数据：', sub);

      // 发送 API 请求
      try {
        const resp = await axiosInstance.post('/api/register/submit', queryString.stringify(sub), {
          headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
        });
        console.log("api/register/submit请求发送成功", resp);
        ElMessage({
          type: 'success',
          message: '挂号成功！',
        });
        resetForm(); // 假设您有一个 resetForm 函数用于重置表单

      } catch (error) {
        console.error("请求失败:", error);
        ElMessage({
          type: 'error',
          message: '挂号失败，请重试！',
        });
      }
    } else {
      console.log('error submit!', fields);
      ElMessage({
        type: 'warning',
        message: '请检查表单填写是否完整！',
      });
    }
  });
};

const department={
  id:0,
  deptCode:'',
  deptName:'',
  deptType:'',
  delmark:''
}
//测试获取部门号为2的部门请求
// 发起一个post请求
// axiosInstance({
//   method: 'get',
//   url: '/department/getDepartmentById',
// });

// 去重函数，根据特定字段去重

</script>






<style lang="css" link-ref="main.css"/>
 <style scoped> 
  h1{
    padding-left: 30px;
    
  }
 .label{
  display: inline-block;
  width: 200px;
   color: grey;
  padding-left: 30px;
  
 }
 el-form{
  label-position:right;
 }
 h3{
  padding-left: 20px;
 }
 .demo-basic {
  text-align: right;
}
.demo-basic .sub-title {
  margin-bottom: 10px;
  font-size: 14px;
  color: var(--el-text-color-secondary);
}
.demo-basic .demo-basic--circle,
.demo-basic .demo-basic--square {
  display: flex;
  justify-content: flex-end;
  align-items: right;
}
.demo-basic .block:not(:last-child) {
  border-right: 1px solid var(--el-border-color);
}
.demo-basic .block {
  flex: 1;
}
.demo-basic .el-col:not(:last-child) {
  border-right: 1px solid var(--el-border-color);
}


</style>